<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>忘记密码</title>
    <link rel="stylesheet" href="assets/css/styles.css">
    <link rel="stylesheet" href="assets/css/common.css">
    <link rel="stylesheet" href="assets/css/auth.css">
    <link rel="stylesheet" href="assets/css/background.css">
    <style>
        .step-2 {
            display: none;
        }
        
        .info {
            background-color: #e0f2fe;
            border: 1px solid #b3e0ff;
            color: #0066cc;
        }
    </style>
</head>
<body>
    <!-- 背景几何图形 -->
    <div class="bg-shapes">
        <div class="shape circle bg-element-1"></div>
        <div class="shape square bg-element-2"></div>
        <div class="shape circle bg-element-3"></div>
        <div class="shape plus bg-element-4">+</div>
        <div class="shape dna bg-element-5"></div>
        <div class="shape circle bg-element-6"></div>
        <div class="shape square bg-element-7"></div>
    </div>

    <!-- 忘记密码表单 -->
    <div class="auth-container">
        <div class="auth-header">
            <h1>忘记密码</h1>
            <p id="step-description">请输入您的邮箱地址以重置密码</p>
        </div>

        <div id="error-message" class="message error" style="display: none;"></div>
        <div id="success-message" class="message success" style="display: none;"></div>

        <!-- 第一步：输入邮箱 -->
        <div id="step-1">
            <div class="form-group">
                <label for="email">邮箱地址</label>
                <input type="email" id="email" name="email" placeholder="请输入您的邮箱地址" required>
            </div>

            <button type="button" class="auth-btn" id="send-code-btn">发送验证码</button>
        </div>

        <!-- 第二步：输入验证码和新密码 -->
        <div id="step-2" class="step-2">
            <div id="email-info" class="message info" style="display: none;">
                <p><strong>验证码已发送至：</strong><span id="user-email"></span></p>
            </div>

            <form id="reset-password-form">
                <div class="form-group">
                    <label for="verificationCode">验证码</label>
                    <input type="text" id="verificationCode" name="verificationCode" placeholder="请输入邮箱收到的验证码" maxlength="6" required>
                </div>

                <div class="form-group">
                    <label for="newPassword">新密码</label>
                    <input type="password" id="newPassword" name="newPassword" placeholder="请输入新密码" minlength="6" required>
                </div>

                <div class="form-group">
                    <label for="confirmPassword">确认密码</label>
                    <input type="password" id="confirmPassword" name="confirmPassword" placeholder="请再次输入新密码" required>
                </div>

                <div class="form-group" style="display: flex; gap: 10px;">
                    <button type="button" class="auth-btn" id="back-btn" style="flex: 1; background-color: #6b7280;">上一步</button>
                    <button type="submit" class="auth-btn" id="reset-btn" style="flex: 1;">重置密码</button>
                </div>
            </form>
        </div>

        <div class="auth-link">
            <a href="login.html">返回登录</a>
        </div>
    </div>

    <script>
        let countdown = 0;
        let countdownTimer;

        document.getElementById('send-code-btn').addEventListener('click', sendVerificationCode);
        document.getElementById('back-btn').addEventListener('click', goBack);
        document.getElementById('reset-password-form').addEventListener('submit', resetPassword);

        async function sendVerificationCode() {
            const email = document.getElementById('email').value;
            const sendBtn = document.getElementById('send-code-btn');
            const errorMessage = document.getElementById('error-message');
            const successMessage = document.getElementById('success-message');

            // 隐藏消息
            errorMessage.style.display = 'none';
            successMessage.style.display = 'none';

            // 表单验证
            if (!email) {
                showError('请输入邮箱地址');
                return;
            }
            
            if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
                showError('请输入有效的邮箱地址');
                return;
            }

            // 禁用按钮
            sendBtn.disabled = true;
            sendBtn.textContent = '发送中...';

            try {
                // 调用发送验证码API
                const response = await fetch('http://localhost:8080/chm/api/auth/send-reset-code', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    mode: 'cors',
                    credentials: 'omit',
                    body: JSON.stringify({
                        email: email
                    })
                });

                const result = await response.json();

                if (result.status === 0) {
                    showSuccess('验证码已发送到您的邮箱，请查收');
                    
                    // 显示第二步
                    document.getElementById('step-1').style.display = 'none';
                    document.getElementById('step-2').style.display = 'block';
                    document.getElementById('step-description').textContent = '请输入验证码并设置新密码';
                    
                    // 显示邮箱信息
                    document.getElementById('user-email').textContent = email;
                    document.getElementById('email-info').style.display = 'block';
                    
                    // 开始倒计时
                    startCountdown();
                } else {
                    showError(result.msg || '发送验证码失败');
                    sendBtn.disabled = false;
                    sendBtn.textContent = '发送验证码';
                }
            } catch (error) {
                showError('网络错误，请检查网络连接');
                console.error('发送验证码请求失败:', error);
                sendBtn.disabled = false;
                sendBtn.textContent = '发送验证码';
            }
        }

        async function resetPassword(e) {
            e.preventDefault();
            
            const email = document.getElementById('email').value;
            const verificationCode = document.getElementById('verificationCode').value;
            const newPassword = document.getElementById('newPassword').value;
            const confirmPassword = document.getElementById('confirmPassword').value;
            const resetBtn = document.getElementById('reset-btn');
            const errorMessage = document.getElementById('error-message');
            const successMessage = document.getElementById('success-message');

            // 隐藏消息
            errorMessage.style.display = 'none';
            successMessage.style.display = 'none';

            // 表单验证
            if (!verificationCode) {
                showError('请输入验证码');
                return;
            }

            if (!newPassword) {
                showError('请输入新密码');
                return;
            }

            if (newPassword !== confirmPassword) {
                showError('两次输入的密码不一致');
                return;
            }

            if (newPassword.length < 6) {
                showError('密码长度至少6位');
                return;
            }

            // 禁用按钮
            resetBtn.disabled = true;
            resetBtn.textContent = '重置中...';

            try {
                // 调用重置密码API
                const response = await fetch('http://localhost:8080/chm/api/auth/reset-password', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    mode: 'cors',
                    credentials: 'omit',
                    body: JSON.stringify({
                        email: email,
                        code: verificationCode,
                        newPassword: newPassword
                    })
                });

                const result = await response.json();

                if (result.status === 0) {
                    showSuccess('密码重置成功！正在跳转到登录页...');
                    
                    // 3秒后跳转到登录页
                    setTimeout(() => {
                        window.location.href = 'login.html';
                    }, 3000);
                } else {
                    showError(result.msg || '密码重置失败');
                    resetBtn.disabled = false;
                    resetBtn.textContent = '重置密码';
                }
            } catch (error) {
                showError('网络错误，请检查网络连接');
                console.error('重置密码请求失败:', error);
                resetBtn.disabled = false;
                resetBtn.textContent = '重置密码';
            }
        }

        function goBack() {
            // 显示第一步
            document.getElementById('step-1').style.display = 'block';
            document.getElementById('step-2').style.display = 'none';
            document.getElementById('step-description').textContent = '请输入您的邮箱地址以重置密码';
            
            // 清除消息
            document.getElementById('error-message').style.display = 'none';
            document.getElementById('success-message').style.display = 'none';
            
            // 重置按钮
            document.getElementById('send-code-btn').disabled = false;
            document.getElementById('send-code-btn').textContent = '发送验证码';
            
            // 停止倒计时
            clearInterval(countdownTimer);
            countdown = 0;
        }

        function startCountdown() {
            countdown = 60;
            const sendBtn = document.getElementById('send-code-btn');
            
            countdownTimer = setInterval(() => {
                countdown--;
                sendBtn.textContent = `重新发送(${countdown}s)`;
                
                if (countdown <= 0) {
                    clearInterval(countdownTimer);
                    sendBtn.disabled = false;
                    sendBtn.textContent = '发送验证码';
                }
            }, 1000);
        }

        function showError(message) {
            const errorMessage = document.getElementById('error-message');
            errorMessage.textContent = message;
            errorMessage.style.display = 'block';
        }

        function showSuccess(message) {
            const successMessage = document.getElementById('success-message');
            successMessage.textContent = message;
            successMessage.style.display = 'block';
        }
    </script>
</body>
</html>